<template>
    <div>
        &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<el-checkbox @change="checkAll">全选</el-checkbox>
        <br/>
        <el-tree ref="tree" 
            :data="menuTree" 
            show-checkbox 
            node-key="id"
            :default-checked-keys="defaultKeys"
            default-expand-all>
            <span slot-scope="{ node, data }">
                <i class="iconfont ali-menu" v-if="data.children && data.children.length > 0"></i>
                <span>{{ node.label }}</span>
            </span>
        </el-tree>
    </div>
</template>
<script>
import { menu_save, menu_deleteByCompanyId } from "@/api/menu";
import { menuTree, ids } from './menu' 

export default {
    name: 'menuSet',
    props: {
        dataTree: Array
    },
    data() {
        return {
            menuTree: menuTree(),
            defaultKeys: []
        }
    },
    methods: {
        checkAll(e){
            this.$refs['tree'].setCheckedKeys(e ? ids : []);
        },
        async submit(){
            //清空菜单
            let { data } = await menu_deleteByCompanyId();
            let nodes = await this.$refs['tree'].getCheckedNodes(false,true);
            for (let i = 0; i < nodes.length; i++) {
                let node = nodes[i];
                let saveObj = {
                    menu_name   : node.label,
                    menu_code   : node.menu_code,
                    menu_url   : node.id,
                    parent_id   : node.pId,
                    company_id  : localStorage.getItem("companyId") - 0,
                    close_status: 1
                }
                await menu_save(saveObj);
            }
            this.$message.success("操作成功")
        },
        formatDefaultKeys(data){
            let result = []
            for (let i = 0; i < data.length; i++) {
                let element = data[i];
                if(element.children && element.children.length > 0){
                    result.push(...this.formatDefaultKeys(element.children))
                }else if(element.menu_url){
                    result.push(element.menu_url)
                }
            }
            return result;
        },
        async initDefault(){
            this.defaultKeys = []
            if(this.dataTree.length != 0){
                this.defaultKeys = [...this.formatDefaultKeys(this.dataTree)];
            }
        }
    }
}
</script>
